package com.bawei.mdm2207alast.sign

import android.annotation.SuppressLint
import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.bawei.mdm2207alast.R
import com.bawei.mdm2207alast.base.OnError
import com.bawei.mdm2207alast.base.OnLoading
import com.bawei.mdm2207alast.base.OnSuccess
import com.bawei.mdm2207alast.common.BaseTitle
import com.bawei.mdm2207alast.model.SelSignEntity
import com.bawei.mdm2207alast.route.RouteConfig
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date

/**
 * 作者：赵亮
 * 时间：2024/12/16 15:38
 * 功能：查询签到记录
 */
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun SelSignPage(
    navController: NavController = rememberNavController(),
    viewModel: SignViewModel = hiltViewModel()
) {

    // 签到按钮显示的是签到 还是签退
    var sign by remember {
        mutableStateOf("签到")
    }

    // 签到按钮是否可用
    var isEnable by remember {
        mutableStateOf(true)
    }

    val mmkv = MMKV.defaultMMKV()
    // 读取签到状态 今天是否有签到记录
    val isSign = mmkv.decodeString("sign", "").toString()
    // 如果签到状态 isEmpty 说明软件是第一次使用
    if (!isSign.isEmpty()) {
        val split = isSign.split(",")
        val format = SimpleDateFormat("yyyy-MM-dd")
        if (format.format(System.currentTimeMillis()) == format.format(split[1].toLong())) {
            if (split[0] == "签到") {
                sign = "签退"
            } else {
                isEnable = false
            }
        }
    }

    // 当前时间
    var time by remember {
        mutableStateOf(Date())
    }

    // 1. 数据
    val list = remember {
        SnapshotStateList<SelSignEntity.Data>()
    }

    LaunchedEffect(key1 = "") {
        launch {
            viewModel.uiState.collect {
                when (it) {
                    is OnError -> {
                        ToastUtils.showShort(it.msg)
                    }

                    OnLoading -> {}
                    is OnSuccess<*> -> {
                        list.addAll((it.data as SelSignEntity).data)
                    }
                }
            }
        }
        launch {
            viewModel.sendIntent(SignIntent.SelSign(mapOf("userId" to 1, "page" to 1)))
        }
        launch {
            while (true) {
                delay(1000)
                time = Date()
            }
        }
    }

    Scaffold(
        bottomBar = {
            // 签到按钮
            Button(
                enabled = isEnable,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 15.dp),
                onClick = {
                    // 跳转到签到页面
                    navController.navigate(RouteConfig.INSERT_SIGN)
                }) {
                val dateFormat = SimpleDateFormat("hh:mm:ss")
                Text(text = "$sign${dateFormat.format(time)}")
            }
        }
    ) {
        Column {
            BaseTitle(navController = navController, title = "考勤")

            Column(modifier = Modifier.padding(start = 15.dp, end = 15.dp, top = 10.dp)) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text(text = "时间${TimeUtils.getChineseWeek(System.currentTimeMillis())}")
                    Text(text = "考勤规则")
                }

                // 展示签到列表
                LazyColumn(modifier = Modifier.padding(top = 10.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
                    items(list) {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(40.dp)
                                .background(
                                    color = colorResource(
                                        id = R.color.sel_sign_item_bg
                                    )
                                )
                        ) {
                            Text(
                                modifier = Modifier
                                    .align(Alignment.CenterStart)
                                    .padding(start = 10.dp),
                                text = SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(it.signTime)
                            )
                        }
                    }
                }
            }
        }
    }
}

@Preview(showSystemUi = true)
@Composable
fun SelSignPagePreview() {
    SelSignPage()
}

